package com.lx.fphonelocation;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.List;

/**
 * 安卓自带定位
 */
public class LocationUtil {
    private volatile static LocationUtil instance;
    //上下文
    private Context mContext;
    //定位回调
    private LocationCallback locationCallback;
    //定位信息
    private Location location;
    //定位管理器
    private LocationManager locationManager;
    //是否多次定位
    private boolean isSingle = true;
    //定位时间间隔
    private int delayMilTime = 5000;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    //开始定位
                    startLocation();
                    break;
            }
        }
    };

    public static LocationUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (LocationUtil.class) {
                if (instance == null) {
                    instance = new LocationUtil(context);
                }
            }
        }
        return instance;
    }

    private LocationUtil(Context context) {
        mContext = context;
    }
    //设置是否循环
    public LocationUtil  setIsSingle(boolean isSingle){
        this.isSingle = isSingle;
        return  this;
    }
    //设置延时时间，以毫秒为单位
    public LocationUtil  setDelayMilTime(int delayMilTime){
        this.delayMilTime = delayMilTime;
        return  this;
    }
    //设置定位回调
    public void setLocationCallback(LocationCallback locationCallback) {
        this.locationCallback = locationCallback;
    }
    //停止定位
    public void stopLocation() {
        try {
            if (locationManager != null) locationManager.removeUpdates(locationListener);
//            if(handler!=null)handler.removeMessages(1);
        }catch (Exception e){

        }
    }
    //开启定位
    public void startLocation() {
        //添加用户权限申请判断
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //1.获取位置管理器
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //2.获取位置提供器，GPS或是NetWork
//        // 获取所有可用的位置提供器
//        Criteria criteria = new Criteria();
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
//        criteria.setAltitudeRequired(true);
//        criteria.setBearingRequired(true);
//        criteria.setSpeedRequired(true);
//        criteria.setCostAllowed(true);
//
//        // Only for Android 3.0 and above
//        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
//        criteria.setVerticalAccuracy(Criteria.ACCURACY_MEDIUM);
//        criteria.setBearingAccuracy(Criteria.ACCURACY_LOW);
//        criteria.setSpeedAccuracy(Criteria.ACCURACY_LOW);
//
//        List<String> providerList = locationManager.getProviders(criteria,true);
        //获取定位提供者集合
        List<String> providerList = locationManager.getProviders(true);
        Log.e("MainActivity", "providerList=" + providerList);
        //优先gps定位
        Location gpsLocation = getGpsLocation(providerList);
        Log.e("MainActivity", "2 gpsLocation=" + gpsLocation);
        if(gpsLocation==null){
            //然后网络定位
            Location netLocation = getNetLocation(providerList);
            Log.e("MainActivity", "2 netLocation=" + netLocation);
            if(netLocation==null){
                // 当没有可用的位置提供器时，弹出Toast提示用户
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                return;
            }
        }
    }

    public Location getGpsLocation(List<String> providerList) {
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            //GPS 定位的精准度比较高，但是非常耗电。
            System.out.println("=====GPS_PROVIDER=====");
            String locationProvider = LocationManager.GPS_PROVIDER;
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
            locationManager.requestSingleUpdate(locationProvider,locationListener, Looper.myLooper());
//            locationManager.requestLocationUpdates(locationProvider, 5000, 0, locationListener);
            location = locationManager.getLastKnownLocation(locationProvider);
            return location;
        }
        return null;
    }
    public Location getNetLocation(List<String> providerList) {
        if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            //网络定位的精准度稍差，但耗电量比较少。
            System.out.println("=====NETWORK_PROVIDER=====");
            String locationProvider = LocationManager.NETWORK_PROVIDER;
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
            locationManager.removeUpdates(locationListener);
            locationManager.requestSingleUpdate(locationProvider,locationListener, Looper.myLooper());
//            locationManager.requestLocationUpdates(locationProvider, 5000, 0, locationListener);
            location = locationManager.getLastKnownLocation(locationProvider);
            return location;
        }
        return null;
    }
    private LocationListener locationListener = new LocationListener() {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location loc) {
            System.out.println("==onLocationChanged==");
            double latitude = loc.getLatitude();
            double longitude = loc.getLongitude();
            //有数据，回调返回
            if(locationCallback != null)locationCallback.onLocation(latitude,longitude);
            if(!isSingle){
                //可以多次定位，则延迟发送消息，进行循环定位
                if(handler!=null)handler.sendEmptyMessageDelayed(1,delayMilTime);
            }
        }
    };

}
